package cn.wolfcode.crm.exception;

import cn.wolfcode.crm.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 该类是对控制器的增强
 * 利用aop代理实现增强
 */
@ControllerAdvice
public class CrmExceptionHandler {
    /**
     * 代表该方法是用户捕获并处理某一种异常
     */
    @ExceptionHandler(RuntimeException.class)
    public String handlerException(RuntimeException re, HandlerMethod method, HttpServletResponse resp) {
        re.printStackTrace();

        //如果原本控制器的方法返回的是JsonResult，出异常页应该返回JsonResult
        //如果原本控制器的方法是返回视图，出异常页应该返回视图
        //获取出现异常的方法，判断是否有ResponseBody注解
        if (method.getMethodAnnotation(ResponseBody.class) != null) {
            try {
                String msg = "操作失败";
                if (re instanceof LogicException) {
                    msg = re.getMessage();
                }

                resp.setContentType("application/json;charset=utf-8");
                resp.getWriter().print(JSON.toJSONString(new JsonResult(false, msg)));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        return "common/error";
    }

    @ExceptionHandler(UnauthorizedException.class)
    public String exceptionHandler(RuntimeException re, HandlerMethod method, HttpServletResponse resp) throws IOException {

        re.printStackTrace();
        if (method.hasMethodAnnotation(ResponseBody.class)) {
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().print(JSON.toJSONString(new JsonResult(false, "没有访问权限")));
            return null;
        }
        return "common/nopermission";
    }
}
